(function($) {
  $.rukanPhoto = {version: '0.0.1'};
	
  $.fn.rukanPhoto = function(settings) {
	settings = jQuery.extend({
		animation_speed: 'slow',
		ajaxcallback: function() {},
		opacity: 0.9, 
		width: 980,
		height: $(window).height(),
		markup: '<div class="pp_container" role="dialog"><div class="pp_loaderIcon"></div><div class="pp_placeholder"></div><div class="pp_arrow_previous"></div><div class="pp_arrow_next"></div></div><div class="pp_overlay"></div>'
	}, settings);
		
	var self = this, windowHeight = $(window).height(), windowWidth = $(window).width();
	var documentHeight = $(document).height();

	/**
	* Initialize rukanPhoto.
	*/
	$.rukanPhoto.initialize = function() {
	  var theRel = $(this).attr('rel');
		
	  // Mảng các href
	  pp_images = jQuery.map(self, function(n, i){ 
		if($(n).attr('rel').indexOf(theRel) != -1) 
		  return $(n).attr('href'); 
	  });
			
	  // Dựa vào mảng các src tính ra item thứ bao nhiêu được click
	  set_position = jQuery.inArray($(this).attr('href'), pp_images);
	  rel_index = $(this).attr('href');
    
	  // Mảng các data-url
	  pp_images_url = jQuery.map(self, function(n, i){ 
		if($(n).attr('rel').indexOf(theRel) != -1) 
		  return $(n).data("url"); 
	  });
	  
	  // Dựa vào mảng các data-url tính ra item thứ bao nhiêu được click
	  set_position_url = jQuery.inArray($(this).data("url"), pp_images_url);
	  rel_index_url = $(this).data("url");
	  
	  _init_popup();
	  
	  $.rukanPhoto.open();
			
	  return false;
	};
		
	function _init_popup() {
   	  $('body').append(settings.markup).css({
   	    overflow: 'hidden'
   	  });
  
	  // Set global selectors, set sau khi append html
	  $pp_container = $('.pp_container'), $pp_overlay = $('.pp_overlay'); 
	  $previous_selector = $('.pp_arrow_previous'), $next_selector = $('.pp_arrow_next');
   	  
	  $pp_overlay.css({
		'height': documentHeight,
		'width': windowWidth
	  }).bind('click', function(){
		$.rukanPhoto.close();
	  });
			
	  $pp_container.find('.pp_arrow_previous').bind('click',function(){
		$.rukanPhoto.changePage('previous');
		return false;
	  });
		
	  $pp_container.find('.pp_arrow_next').bind('click',function(){
		$.rukanPhoto.changePage('next');
		return false;
	  });
			
	  // Thiết lập vị trí center và kích cỡ cho popup
	  scroll_pos = _get_scroll();
  
	  var top = '';
	  top = (windowHeight/2) + scroll_pos['scrollTop'] - (settings.height.toString()/2) - 10;
	  
	  if (scroll_pos['scrollTop'] == 0 || top < 0) {
		  top = 0;
	  }
	  
	  $pp_container.css({
		top: top,
		left: (windowWidth/2) + scroll_pos['scrollLeft'] -  (settings.width.toString()/2),
		width: settings.width.toString(),
		// height: settings.height.toString()
	  });

    };
		
	/**
	* Opens the rukanPhoto modal box.
	*/
    $.rukanPhoto.open = function(data){
  	  if(data){ // Means it's an API call, need to manually get the settings and set the variables
  		pp_images = $.makeArray(arguments[0]);
  		set_position = 0;
  		pp_images_url = $.makeArray(arguments[1]);
  		set_position_url = 0;
  		
  		rel_index = arguments[0];
  		rel_index_url = arguments[1];
  		
  		_init_popup();
  	  }
    	
      $('.pp_loaderIcon').show();
	  
	  $pp_overlay.fadeTo(settings.animation_speed, settings.opacity);
	  
	  setHashtag();
	  
	  // Fade the placeholder
	  $pp_container.fadeIn(function(){
		$.get(pp_images[set_position], function(responseHTML){
		  $pp_container.find('.pp_placeholder')[0].innerHTML = responseHTML;
		  $('.pp_loaderIcon').hide();        
		  
		  $pp_container.animate({
		    left: windowWidth/2 - settings.width.toString()/2
		  },settings.animation_speed,function() {
		    $next_selector.css('display', 'block');	      
		    $previous_selector.css('display', 'block');
		    $previous_selector.animate({
		      left: -66
			},settings.animation_speed);
			$next_selector.animate({
			  right: -66
			},settings.animation_speed);
		  });
		  
		  settings.ajaxcallback();
		  
		});
      });
			
	  return false;
	};
	
	/**
	* Change page in the rukanPhoto modal box
	* @param direction {String} Direction of the paging, previous or next.
	*/
	$.rukanPhoto.changePage = function(direction){		
      $next_selector.css('right', 0);	      
      $previous_selector.css('left', 0);	
	  if(direction == 'previous') {
		set_position--;
		if (set_position < 0) set_position = $(pp_images).size()-1;

		rel_index_url = pp_images_url[set_position];
		
	    // Hide the content
	    $pp_container.animate({
	      left: windowWidth + 66
	    },settings.animation_speed,function(){
	      $pp_container.css('left', - settings.width.toString() - 66);	 
	      $('.pp_loaderIcon').show();
	      $.rukanPhoto.open();
	    });  
	  } else if(direction == 'next'){
		set_position++;
		if(set_position > $(pp_images).size()-1) set_position = 0;

		rel_index_url = pp_images_url[set_position];
		
	    // Hide the content
	    $pp_container.animate({
	      left: - settings.width.toString() - 66
	    },settings.animation_speed,function(){
	      $pp_container.css('left', windowWidth + 66);	 
	      $('.pp_loaderIcon').show();
	      $.rukanPhoto.open();
	    });       
	  }
	};

	/**
	* Closes rukanPhoto.
	*/
	$.rukanPhoto.close = function(){			
	  $('div.pp_container').fadeOut(settings.animation_speed,function(){
	 	$(this).remove(); 
	  });
	  $pp_overlay.fadeOut(settings.animation_speed, function(){
		$(this).remove();
		delete settings;
		clearHashtag();
	  });
   	  $('body').css({
 	    overflow: 'auto'
 	  });
	};
	
	function _get_scroll(){
	  if (self.pageYOffset) {
		return {scrollTop:self.pageYOffset,scrollLeft:self.pageXOffset};
	  } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
		return {scrollTop:document.documentElement.scrollTop,scrollLeft:document.documentElement.scrollLeft};
	  } else if (document.body) {// all other Explorers
		return {scrollTop:document.body.scrollTop,scrollLeft:document.body.scrollLeft};
	  };
	};

	// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
	return this.unbind('click.rukanPhoto').bind('click.rukanPhoto', $.rukanPhoto.initialize);
  };	
  
  function setHashtag(){
	history.pushState('', '', rel_index_url);
  };
	
  function clearHashtag(){
	var tempArr = rel_index_url.split('\/');
	//console.log(tempArr);
        if(typeof tempArr[1] != "undefined") {
            history.pushState('', '', '/' + tempArr[1]);
        } else {
            
        }
  }
  
})(jQuery);